<?php

namespace App\Controller\App;

use App\Base\BaseController4Restful;
use App\Repository\AnnounceRepository;
use App\Repository\ArticleRepository;
use App\Repository\CategoryRepository;
use App\Repository\CommentRepository;
use App\Repository\ProductRepository;
use Symfony\Component\Routing\Annotation\Route;
use function Doctrine\ORM\QueryBuilder;

class CommentController extends BaseController4Restful
{
    /**
     * @Route("/app/get/comments", name="AppGetComments")
     */
    public function AppGetComments(CommentRepository $commentRepository)
    {
        if(!$what = $this->getParamRequired("what")){return $this->json_out(200,"",[]);}
        if(!$page = $this->getParamRequired("page")){$page = 1;}
        $data = $commentRepository->getByWhat($what,$page);
        $this->setGroups("comment","user");
        return $this->json_out(200,"OK",$data);
    }
    /**
     * @Route("/app/my/comments", name="AppGetMyComments")
     */
    public function AppGetMyComments(CommentRepository $commentRepository)
    {
        if(!$page = $this->getParamRequired("page")){$page = 1;}
        $user =$this->needToBeUser();
        $data = $commentRepository->getByWho($user->getId(),$page);
        $this->setGroups("comment","user");
        return $this->json_out(200,"OK",$data);
    }
    /**
     * @Route("/app/my/comments/del", name="AppGetMyCommentsDelete")
     */
    public function AppGetMyCommentsDelete(CommentRepository $commentRepository,ArticleRepository $articleRepository)
    {
        if(!$id = $this->getParamRequired("id")){return $this->json_out(400,"参数错误");}
        $user =$this->needToBeUser();
        $data = $commentRepository->find($id);
        if (!$data || $data->getWho() != $user) {
            return $this->json_out(500,"系统错误");
        }

        $artId = $data->getWhat();
        $art = $articleRepository->find($artId);
        if ($art) {
            $art->setView( $art->getView() -1);
        }
        $this->myEm()->persist($art);
        $this->myEm()->remove($data);
        $this->myEm()->flush();
//        $this->setGroups("comment","user");
        return $this->json_out(200,"OK");
    }
}
